package com.qust.EnDecryption.util.net.typeConversation;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qust.agreement.result.Result;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class FastJson2PoJo implements IConversation{

    @Override
    public <T> Result<?> conversation(Class<T> type, Object data) {
        return typeConversion(type,(Result<?>) data);
    }

    private <T> Result<?> typeConversion(Class<T> type, Result<?> result){
        if (result.getData() instanceof JSONArray){

            Result<ArrayList<T>> returnResult = new Result<>();
            returnResult.setCode(result.getCode());
            returnResult.setMessage(result.getMessage());

            JSONArray jsonArray = (JSONArray) result.getData();
            ArrayList<T> arrayList = new ArrayList<>();
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                try {
                    arrayList.add(getTObject(type,jsonObject));
                } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            returnResult.setData(arrayList);
            return returnResult;
        }else if (result.getData() instanceof JSONObject){

            Result<T> returnResult = new Result<>();
            returnResult.setCode(result.getCode());
            returnResult.setMessage(result.getMessage());

            try {
                returnResult.setData(getTObject(type,(JSONObject) result.getData()));
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
            return returnResult;
        }
        return null;

    }

    private <T> T getTObject(Class<T> type,JSONObject jsonObject) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        T TObject = type.newInstance();
        Field[] fields = type.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            // 字符串拼接,执行属性的set方法
            String setField = "set"+String.valueOf(fieldName.charAt(0)).toUpperCase()+fieldName.substring(1);
            String fieldValue = String.valueOf(
                    jsonObject.get(fieldName)
            ) ;

            Method method = type.getMethod(setField,String.class);
            method.invoke(TObject,fieldValue);
        }
        return TObject;
    }
}
